import { View, Input, Image } from "@tarojs/components";
import { FC, useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import request from "@/utils/request";
import { AtButton, AtForm, AtInput } from "taro-ui";
import Form, { Field, useForm } from "rc-field-form";
import { HIcon } from "@/components";
import { validateErrorHandler } from "@/utils/validate";
import { useRequest, useCountDown } from "ahooks";
import { formatQueryParams, validatePhone } from "@/utils/util";
import { fetchCode } from "@/service/common";
import { PageParams } from "../type";
import styles from "./index.module.less";
import { tabbarPages } from "@/app.config";
import {
  AccessTokenRequest,
  CodeLoginReqeust,
  LoginResponse,
} from "@/service/type";
import { fetchAccessToken, fetchAccessTokenWithCode } from "@/service/login";
import useAppAction from "@/hooks/useAppAction";

interface Formdata {
  username: string;
  password: string;
  code: number;
}

interface Props {
  /**是否阅读协议 */
  isChecked: boolean;
  /**切换微信登录 */
  onSwitchWechat: () => void;
}

const WechatLogin: FC<Props> = ({ isChecked, onSwitchWechat }) => {
  const { params: pageParams } = useRouter<PageParams>();
  const refresh = useAppAction((action) => action.refresh);
  const [form] = useForm<Formdata>();
  // 0:未发送验证码 1:验证码倒计时 2:重新发送
  const [state, setState] = useState<0 | 1 | 2>(0);
  const [countdown, setCountdown] = useCountDown({
    onEnd() {
      setState(2);
    },
  });

  const { loading, run: login } = useRequest(
    (params: AccessTokenRequest) => fetchAccessToken(params),
    {
      manual: true,
      onSuccess: ({ res }) => {
        console.log("res", res);

        res && loginSuccess(res);
      },
    }
  );

  /**获取验证码 */
  const onQueryCode = async () => {
    const username = form.getFieldValue("username");
    if (!validatePhone(username)) {
      return Taro.showToast({ title: "请输入正确的手机号", icon: "none" });
    }
    Taro.showLoading({ title: "发送中" });
    const result = await fetchCode({
      mobile: username,
      smsSign: "龙池牡丹",
      smsType: "mobile_login",
    });
    Taro.hideLoading();
    if (result.res) {
      const targetDate = Date.now() + 60 * 1000;
      setCountdown(targetDate);
      setState(1);
    }
    if (result.err) {
      setState(2);
    }
  };

  /**提交 */
  const onSubmit = () => {
    const params = form.getFieldsValue();
    if (!isChecked) {
      return Taro.showToast({ title: "请先阅读协议", icon: "none" });
    }
    login({
      // grant_type: "mobile",
      // mobile: "SMS@" + params.username,
      // code: String(params.code),
      grant_type: "password",
      username: params.username,
      password: params.password,
    });
  };

  /**登录成功后逻辑处理 */
  const loginSuccess = async (result: LoginResponse) => {
    request.setToken(result.access_token);
    await refresh();
    // TODO 暂时先直接跳转到完善信息页
    // return Taro.navigateTo({
    //   url: "/package/member/individuation/index",
    // });
    if (!pageParams.redirectUrl) {
      Taro.reLaunch({
        url: "/pages/index/index",
      });
      return;
    }
    const prevPagePath = pageParams.redirectUrl;
    const params =
      pageParams.params &&
      decodeURIComponent(decodeURIComponent(pageParams.params));
    const prevPageParams = params && JSON.parse(params);
    if (prevPagePath.indexOf("pages/login/index") === -1) {
      // 判断是不是tabbar页面
      const isTabbar = tabbarPages.some(
        (item) => prevPagePath.indexOf(item) !== -1
      );
      if (isTabbar) {
        console.log(prevPagePath);
        Taro.switchTab({
          url: `/${prevPagePath}`,
        });
      } else {
        Taro.redirectTo({
          url: `/${prevPagePath + formatQueryParams(prevPageParams)}`,
        });
      }
    }
  };

  /**处理发送验证码按钮状态 */
  function renderQueryCodeBtn() {
    if (state === 0) {
      return (
        <AtButton className={styles["code-btn"]} onClick={onQueryCode}>
          获取验证码
        </AtButton>
      );
    }
    if (state === 1) {
      return (
        <AtButton className={styles["code-btn"]} disabled>
          {Math.round(countdown / 1000)}s后重试
        </AtButton>
      );
    }
    return (
      <AtButton className={styles["code-btn"]} onClick={onQueryCode}>
        重新获取
      </AtButton>
    );
  }

  return (
    <>
      <View className={styles["logo"]}>
        <Image
          className={styles["img"]}
          src={require("@/assets/img/xiangqin-logo.png")}
        />
      </View>
      <Form
        className={styles["form"]}
        form={form}
        component={View}
        onFinishFailed={validateErrorHandler}
        onFinish={onSubmit}
        initialValues={{ username: "18325924003" }}
      >
        <View className={styles["input-wrapper"]}>
          <Field
            name="username"
            trigger="onInput"
            rules={[{ required: true, message: "请输入手机号" }]}
          >
            <Input
              type="text"
              className={styles["input"]}
              placeholder="请输入手机号"
              placeholderStyle="color:#999"
              maxlength={13}
            ></Input>
          </Field>
          <View className={styles["icon"]}>
            <HIcon type="yonghuming" color="#999"></HIcon>
          </View>
        </View>

        <View className={styles["input-wrapper"]}>
          <Field
            name="password"
            trigger="onInput"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input
              className={styles["input"]}
              password
              placeholder="请输入密码"
              placeholderStyle="color:#999"
              maxlength={20}
            ></Input>
          </Field>
          <View className={styles["icon"]}>
            <HIcon type="tianchongxing-" color="#999"></HIcon>
          </View>
        </View>

        {/* <View className={styles["input-wrapper"]}>
          <Field
            name="code"
            trigger="onInput"
            rules={[{ required: true, message: "请输入验证码" }]}
          >
            <Input
              type="number"
              className={styles["input"]}
              placeholder="请输入验证码"
              placeholderStyle="color:#999"
              maxlength={4}
            ></Input>
          </Field>

          <View className={styles["icon"]}>
            <HIcon type="yanzhengma" color="#999"></HIcon>
          </View>
          {renderQueryCodeBtn()}
        </View> */}
        <AtButton
          className={styles["btn"]}
          loading={loading}
          disabled={loading}
          onClick={form.submit}
        >
          登录
        </AtButton>
        <AtButton className={styles["btn2"]} onClick={onSwitchWechat}>
          去注册
        </AtButton>
      </Form>

      {/* <View className={styles["wechat"]} onClick={onSwitchWechat}>
        <HIcon type="weixin" color="#16D46B" size={62}></HIcon>
      </View> */}
    </>
  );
};

export default WechatLogin;
